<template>
  <div class="win">
    <!-- <frames title="订单确认"></frames> -->
    <div class="goods_box">
      <div class="item" v-for="(item,index) in commodity" :key="index">
        <div class="img_box">
          <img :src="item.image" class="img_src" />
        </div>
        <div class="item_top_right">
          <p class="name ellipsis2">{{item.name}}</p>
          <div class="tips_box">
            <p
              v-if="l<2"
              :class="ite=='包邮'?'blue':'green'"
              v-for="(ite, l) in item.label"
              :key="l"
            >{{ite}}</p>
          </div>
          <p class="money_logo1">
            ¥
            <span>{{item.price}}</span>
          </p>
          <div class="commit_row">
            <img class="reduce" @click="reduceNum(index)" src="/static/img/reduce_logo.png" />
            <p class="num">{{item.num}}</p>
            <img class="add" @click="addNum(index)" src="/static/img/add_logo.png" />
          </div>
        </div>
      </div>
    </div>

    <div class="list_box">
      <div class="listt" v-if="order.voucher_num!==0">
        <p class="textLeft black">优惠券:</p>
        <div class="coupon_box">
          <p class="tap_list" @click="tapDeleteCoupon" v-if="couponRow.voucher_id !=undefined">取消使用</p>
          <p
            class="textRight coupon"
            @click="hr_coupon(order.total_price)"
            v-if="couponRow.voucher_id !=undefined"
          >{{couponRow.name}}</p>
          <p
            class="textRight coupon"
            @click="hr_coupon(order.total_price)"
            v-else
          >您有{{order.voucher_num}}张优惠券</p>
          <img class="right_logo" v-if="bjurl" :src="bjurl+'two_right_logo.png'" />
        </div>
      </div>
      <div class="listt" v-else>
        <p class="textLeft black">优惠券:</p>
        <div class="coupon_box">
          <p class="textRight greyy">暂无可用优惠券</p>
          <!-- <img class="right_logo" v-if="bjurl" :src="bjurl+'two_right_logo.png'" /> -->
        </div>
      </div>
      <div class="listt">
        <p class="textLeft">选择物流</p>
        <div class="logistics_box">
          <p class="textRight" v-if="order.logistic_name!=null">{{order.logistic_name}}</p>
          <div @click="hr_expressChoose(current)" class="logistics">
            <p>{{order.logistic_name==null?'去选择':'去修改'}}</p>
            <img class="right_logo" v-if="bjurl" :src="bjurl+'two_right_logo.png'" />
          </div>
        </div>
      </div>
      <div class="listt">
        <p class="textLeft">订单编号:</p>
        <p class="textRight">{{order_number}}</p>
      </div>
      <!-- <div class="listt" v-if="couponRow.voucher_id !== undefined"> -->
      <div class="listt" v-if="orderMoney!=0">
        <p class="textLeft">优惠金额:</p>
        <p class="textRight">￥{{orderMoney}}</p>
      </div>
    </div>
    <div class="tabbar_space"></div>
    <div class="tabbar">
      <div class="price_box">
        <p class="title">共计金额：</p>
        <p class="price">
          ￥
          <span>{{totalPrice}}</span>
        </p>
      </div>
      <button v-if="disabled" @click="payConfirm(order.logistic_name)" class="pay">提交订单</button>
      <button v-else class="pay">提交订单</button>
    </div>
    <i-toast id="toast" />
  </div>
</template>

<script>
export default {
  data() {
    return {
      disabled: true,
      bjurl: "",
      order: {},
      orderMoney: 0,
      order_id: 0, //订单ID
      express: "", //快递名称
      type: "", //商品类型：1 正常商品 2 推荐商品 3 特价商品
      voucher_id: "", //卡券ID
      logistic_id: null, //物流ID
      current: 0, //切换物流默认第一个0
      commodity: [], //商品集合
      order_number: "", //订单编号
      couponRow: {}, //使用的卡券容器
      payLoading: false,
      ispaySuccess: false, //防止多次调用成功支付方法
      payTime: null //轮巡支付成功状态
    };
  },
  methods: {
    // 取消支付遮罩
    hidePayLoading() {
      this.payLoading = false;
      this.$toast.hide();
    },
    // 开启支付遮罩层
    showPayLoading() {
      this.payLoading = true;
      this.$toast({
        content: "支付中",
        type: "loading",
        mark: false,
        duration: 0
      });
    },
    // 支付成功
    paySuccess() {
      // 防止多次调用 /Orders/paySuccess
      if (this.ispaySuccess) {
        return this.$toast({
          content: "支付成功,订单异常,请至我的订单查看"
        });
      }
      this.ispaySuccess = true;
      this.$ajax("/home/order/paySuccess", "post", {
        orderNum: this.order_number,
        orderId: this.order_id,
        price: this.totalPrice
      })
        .then(res => {
          // 支付成功!
          this.hidePayLoading();
          this.hr_paySuccess(res);
        })
        .catch(err => {});
    },
    // 轮巡支付成功状态
    setTimePay() {
      /* 
        0 => 支付失败
        1 => 支付成功
        2 => 支付取消
      */

      this.showPayLoading(); //开启支付遮罩
      let count = 0;
      this.payTime = setInterval(() => {
        this.disabled = true;
        this.$ajax("/home/Wxpay/checkStatus", "post", {
          order_number: this.order_number
        })
          .then(res => {
            if (res.status) {
              if (res.status == 0) {
                // 支付失败,继续轮巡
                if (count > 150) {
                  // 支付超时
                  clearInterval(this.payTime);
                  this.hidePayLoading();
                  wx.showToast({
                    title: "支付失败",
                    icon: "none"
                  });
                }
                count++;
              } else if (res.status == 1) {
                // 支付成功
                clearInterval(this.payTime);
                this.$toast({
                  content: "支付成功~"
                });
                wx.reLaunch({
                  url: "/pages/paySuccess/main?total_price=" + this.totalPrice
                });
                // this.paySuccess();
              } else if (res.status == 2) {
                // 取消支付
                clearInterval(this.payTime);
                this.hidePayLoading();
              }
            } else {
            }
          })
          .catch(err => {});
      }, 2000);
    },
    // 请求微信支付接口
    ordersPay() {
      this.$ajax("/home/order/ordersPay", "post", {
        order_number: this.order_number,
        price: this.totalPrice,
        openid: wx.getStorageSync("open_id")
      })
        .then(res => {
          if (res.return_code) {
            // 调起微信支付
            // 开始轮询
            this.setTimePay();
            wx.requestPayment({
              ...res.return_msg,
              success: res => {
                // clearInterval(payTime);
                // this.$toast({
                //   content: "支付成功~"
                // });
                // wx.reLaunch({
                //   url: "/pages/paySuccess/main?total_price=" + this.totalPrice
                // });
              },
              fail: res => {
                clearInterval(this.payTime);
                this.$toast({
                  content: "取消支付~"
                });
              }
            });
          } else {
            this.$toast({
              content: "支付出错"
            });
            setTimeout(() => {
              this.hr_myOrder();
            }, 500);
          }
        })
        .catch(err => {});
    },
    //请求接口订单确认页
    getOrderConfirm() {
      this.$ajax("/home/order/orderConfirm", "post", {
        order_id: this.order_id,
        type: this.type,
        logistic_id: this.logistic_id,
        voucher_id: this.voucher_id
        // voucher_id:1,
      })
        .then(res => {
          if (res.status) {
            this.commodity = res.data;
            this.order = res.order;
            this.$forceUpdate();
          } else {
          }
        })
        .catch(err => {});
    },
    // 请求接口修改数量
    getOrderNum(num, type, index) {
      this.$ajax("/home/order/orderWriteNum", "post", {
        order_id: this.order_id,
        odetail_id: this.commodity[index].odetail_id,
        num: num,
        type: type
      })
        .then(res => {
          if (res.status) {
            this.getOrderConfirm();
          } else {
          }
        })
        .catch(err => {});
    },
    // 请求接口优惠券使用
    getCouponUse() {
      this.$ajax("/home/voucher/voucher_use", "post", {
        voucher_id: this.voucher_id
      })
        .then(res => {
          if (res.status) {
            this.couponRow = res.data;
          } else {
          }
        })
        .catch(err => {});
    },
    //跳转物流选择
    hr_expressChoose(current) {
      wx.navigateTo({
        url: "../expressChoose/main?current=" + current
      });
    },
    // ++
    addNum(index) {
      this.getOrderNum(++this.commodity[index].num, 1, index);
      this.$forceUpdate();
    },
    // --
    reduceNum(index) {
      if (this.commodity[index].num == 1) {
        this.$forceUpdate();
        return this.$toast({
          content: "已经是最少了"
        });
      }
      this.getOrderNum(--this.commodity[index].num, 2, index);
      this.$forceUpdate();
    },
    // 确认支付
    payConfirm(logistic_name) {
      this.disabled = false;
      if (logistic_name == null) {
        this.disabled = true;
        return this.$toast({
          content: "请选择物流"
        });
      }
      this.ordersPay();
      // wx.navigateTo({
      //   url: "../paySuccess/main?type=0&order_money=" + this
      // });
    },
    // 取消选择优惠券
    tapDeleteCoupon() {
      this.couponRow = {};
      this.voucher_id = "";
      this.$forceUpdate();
    },
    // 跳转到选择优惠券
    hr_coupon(total_price) {
      //  把当前金额带过去,判断某些优惠券能否使用
      wx.navigateTo({
        url: "../coupon/main?total_price=" + total_price + "&order_type=" + 1
      });
    },
    // 跳转订单页(支付出错时调用)
    hr_myOrder() {
      wx.reLaunch({
        url: "../myOrder/main?current=" + 0
      });
    },
    // 监听物流信息
    monitorWuliuInfo() {
      this.$bus.$on("wuliuInfo", info => {
        this.express = info.express;
        this.logistic_id = info.logistic_id;
        this.current = info.current;
      });
    },
    // 监听优惠券信息
    monitorCoupon() {
      this.$bus.$on("couponInfo", info => {
        this.voucher_id = info.voucher_id;
      });
    }
  },
  computed: {
    totalPrice() {
      var totalPrice = 0;
      this.orderMoney = 0;
      this.commodity.forEach((el, i) => {
        totalPrice += el.price * el.num;
      });
      // 价格变动的时候看优惠券是否还可以使用
      if (this.couponRow.voucher_id != undefined) {
        if (
          totalPrice < this.order.full_money &&
          totalPrice < this.order.active_money_off
        ) {
          this.orderMoney = 0;
          this.couponRow = {};
          // this.getOrderConfirm();
          this.$forceUpdate();
          return (totalPrice = totalPrice.toFixed(2));
        }
        else if (totalPrice < this.couponRow.full_money) {
          this.voucher_id = "";
          this.orderMoney = 0;
          this.couponRow = {};
          return (totalPrice = totalPrice.toFixed(2));
        }
        totalPrice -= this.order.money;
        this.orderMoney =
          parseInt(this.orderMoney) + parseInt(this.order.money);
        // 如果价格低于满减标准,则取消选择该优惠券
      }
      if (totalPrice >= this.order.active_money_off) {
        totalPrice -= this.order.active_price;
        this.orderMoney =
          parseInt(this.orderMoney) + parseInt(this.order.active_price);

        this.$forceUpdate();
      }
      return (totalPrice = totalPrice.toFixed(2));
      this.$forceUpdate();
      // if (totalPrice[totalPrice.length - 1] === "0") {
      //   return parseFloat(totalPrice).toFixed(1);
      // } else {
      //   return totalPrice;
      // }
    }
  },
  onShow() {
    this.getCouponUse();
    this.getOrderConfirm();
    this.disabled = true;
  },
  onLoad(e) {
    Object.assign(this.$data, this.$options.data());
    this.bjurl = this.$bjurl;
    this.type = e.type;
    this.$navColor({
      title: "订单确认"
    });
    this.order_id = e.order_id;
    this.order_number = e.order_number;
    this.monitorWuliuInfo();
    this.monitorCoupon();
  }
};
</script>

<style lang="scss" scoped>
.win {
  .goods_box {
    border-radius: 10rpx;
    padding-top: 20rpx;
    width: 750rpx;
    .item {
      font-weight: 500;
      margin-bottom: 20rpx;
      display: flex;
      box-sizing: border-box;
      overflow: hidden;
      background-color: #ffffff;
      width: 750rpx;
      padding: 15rpx 0;
      box-shadow: -1rpx 7rpx 8rpx 0rpx rgba(169, 169, 169, 0.14);
      .img_box {
        margin-left: 15rpx;
        .img_src {
          width: 198rpx;
          height: 198rpx;
          border-radius: 10rpx;
        }
      }

      .item_top_right {
        flex: 1;
        box-sizing: border-box;
        position: relative;
        padding-top: 10rpx;
        padding-left: 20rpx;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        .commit_row {
          position: absolute;
          right: 24rpx;
          bottom: 0rpx;
          $h: 38rpx;
          display: flex;
          align-items: center;
          img {
            width: 48rpx;
            height: 48rpx;
          }
          p {
            font-size: 35rpx;
            line-height: $h;
            height: $h;
            padding: 0 20rpx;
            color: #333333;
            font-weight: bold;
          }
        }
        .name {
          font-size: 30rpx;
          width: 520rpx;
        }
        .tips_box {
          display: flex;
          p {
            padding: 6rpx 10rpx 7rpx;
            font-size: 20rpx;
            border-radius: 20rpx;
            margin-right: 10rpx;
          }
          .blue {
            color: #6da9ff;
            background-color: #deebff;
            border-radius: 15rpx;
            margin-right: 10rpx;
          }
          .green {
            color: #ffffff;
            background-color: $green;
          }
        }
        .money_logo1 {
          color: $red;
          font-size: 30rpx;
          span {
            font-size: 45rpx;
          }
        }
      }
    }
  }
}

.list_box {
  overflow: hidden;
  margin-bottom: 20rpx;
  background-color: #ffffff;
  font-weight: 500;
  font-size: 26rpx;
  box-shadow: -1rpx 7rpx 8rpx 0rpx rgba(169, 169, 169, 0.14);
  .listt {
    height: 90rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 30rpx;
    box-sizing: border-box;
    font-weight: 500;
    font-size: 28rpx;
    color: #999999;
    margin-bottom: 2rpx;
    box-shadow: 0rpx -1rpx 0rpx 0rpx rgba(240, 240, 240, 1);
    .textLeft {
      color: #333333;
    }
    .textRight {
      color: #4d4d4d;
    }
    .coupon_box {
      display: flex;
      align-items: center;
      .tap_list {
        margin-right: 20rpx;
        text-decoration: underline;
      }
      .right_logo {
        margin-left: 6rpx;
        width: 20rpx;
        height: 22rpx;
      }
      .greyy {
        color: #4d4d4d;
      }
      .coupon {
        color: $green;
      }
    }
    .logistics_box {
      display: flex;
      align-items: center;
      .logistics {
        margin-left: 45rpx;
        display: flex;
        align-items: center;
        color: $green;
      }
      .right_logo {
        margin-left: 6rpx;
        width: 20rpx;
        height: 22rpx;
      }
    }
  }
}
.tabbar_space {
  height: 160rpx;
}
.tabbar {
  height: 100rpx;

  background-color: #ffffff;
  display: flex;
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding-left: 60rpx;
  box-sizing: border-box;
  justify-content: space-between;
  align-items: center;
  .price_box {
    display: flex;
    font-size: 28rpx;
    color: #4d4d4d;
    align-items: flex-end;
    .title {
      line-height: 1.3;
    }
    .price {
      font-size: 28rpx;
      color: $red;
      span {
        font-size: 40rpx;
      }
    }
  }
  .pay {
    width: 292rpx;
    height: 100rpx;
    background: linear-gradient(
      0deg,
      rgba(11, 208, 94, 1),
      rgba(11, 208, 173, 1)
    );
    font-size: 36rpx;
    color: #ffffff;
    letter-spacing: 3rpx;
    line-height: 100rpx;
    border-radius: 0rpx;
  }
}
</style>
